package media

import (
	"errors"
	"server/common"

	"github.com/mitchellh/mapstructure"
)

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) checkCloseRouterReqData(data common.CloseRouterReqData) error {
	// Check if worker ID is provided
	if data.WorkerId == 0 {
		return errors.New("worker ID is required in close router request")
	}

	// Check if service ID is provided
	if data.ServiceId == "" {
		return errors.New("service ID is required in close router request")
	}

	// Check router ID if provided
	if data.RouterId == "" {
		return errors.New("router ID is required in close router request")
	}

	// Check if worker exists
	if !s.workerMgr.WorkerExists(data.WorkerId) {
		return errors.New("worker does not exist")
	}

	// Check if service exists
	if s.serviceId != data.ServiceId {
		return errors.New("service does not exist")
	}

	return nil
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) sendCloseRouterResponse(rid string, code int, msg string,
	data common.CloseRouterReqData) {
	res := common.Message{
		Cmd: common.CLOSE_ROUTER_RES,
		Rid: rid,
		Data: common.ResMsgData{
			Code: code,
			Msg:  msg,
			Data: common.CloseRouterResData{
				RouterId:  data.RouterId,
				ServiceId: data.ServiceId,
				WorkerId:  data.WorkerId,
			},
		},
	}

	if err := s.wsClient.Send(res); err != nil {
		LOG().WithError(err).Error("Failed to send close router response")
	}
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) handleCloseRouterReq(msg common.Message) error {
	var reqData common.CloseRouterReqData
	if err := mapstructure.Decode(msg.Data, &reqData); err != nil {
		return errors.New("failed to decode close router request data: " + err.Error())
	}

	// Validate request data
	if err := s.checkCloseRouterReqData(reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("Invalid close router request data")
		s.sendCloseRouterResponse(msg.Rid, 1, err.Error(), reqData)
		return nil
	}

	// Close the router
	if err := s.CloseRouter(msg.Rid, reqData.RouterId, reqData.WorkerId); err != nil {
		LOG(msg.Rid).WithError(err).Error("Failed to close router")
		s.sendCloseRouterResponse(msg.Rid, 1, err.Error(), reqData)
		return nil
	}

	// Send response
	s.sendCloseRouterResponse(msg.Rid, 0, "Router closed successfully", reqData)

	return nil
}
